package team.epos.utils.jms;

import java.io.Serializable;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ActiveMQutil {

    private static ActiveMQutil activeMQutil = null;

    static {
        activeMQutil = new ActiveMQutil();
    }

    private ActiveMQutil() {
    }

    public static ActiveMQutil getActiveMQutil() {
        return activeMQutil;
    }


    private ConnectionFactory connectionFactory = null;
    private Connection connection = null;
    private Session session = null;
    private Destination destination = null;
    private MessageProducer messageProducer = null;
    private MessageConsumer messageConsumer = null;


    /**
     * 初始化链接工厂和链接
     *
     * @param userName
     * @param passWord
     * @param url
     */
    public void setConnectionFactory(String userName, String passWord, String url) {
        connectionFactory = new ActiveMQConnectionFactory(userName, passWord, url);
        try {
            connection = connectionFactory.createConnection();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    /**
     * 消息中间件发送消息方法
     *
     * @param queueName 队列名称
     */
    public void setProducerP2p(String queueName, String Message) {
        try {
            session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            destination = session.createQueue(queueName);
            messageProducer = session.createProducer(destination);
            TextMessage text = session.createTextMessage(Message);
            messageProducer.send(text);
            System.out.println(text.getText());
            text.acknowledge();
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            closeConnection(connection);
        }

    }


    /**
     * 消息中间件接收消息方法
     *
     * @param queueName 队列名称
     */
    public void setCustomerP2p(String queueName, GetAClientMethod getAClientMethod) {
        try {
            connection.start();
            session = connection.createSession(Boolean.FALSE, Session.CLIENT_ACKNOWLEDGE);
            destination = session.createQueue(queueName);
            messageConsumer = session.createConsumer(destination);
            messageConsumer.setMessageListener(new ActiveMQListener(getAClientMethod));
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }


    /**
     * 关闭链接
     *
     * @param connection 链接
     */
    public void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }

}